package com.test.shiro.realm;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;

import com.test.common.entity.UUser;
import com.test.shiro.token.TokenManager;

@SuppressWarnings("all")
public class MyRealm extends AuthorizingRealm{
	/**
	 * 为当限前登录用户作认证和授权处理
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		Long userId = TokenManager.getUserId();
		SimpleAuthorizationInfo info =  new SimpleAuthorizationInfo();
		//根据用户ID查询角色（role），放入到Authorization里。
		//Set<String> roles = roleService.findRoleByUserId(userId);
		//info.setRoles(roles);
		//根据用户ID查询权限（permission），放入到Authorization里。
		//Set<String> permissions = permissionService.findPermissionByUserId(userId);
		Set<String> permissions = new HashSet<>();
		permissions.add("member");
		permissions.add("permission");
		info.setStringPermissions(permissions);
        return info;  
	}
	/**
	 * 验证当前登录的用户
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String userEname = (String)token.getPrincipal();
		UUser user = getUser(userEname);
		if(null == user){
			/**
			 * 如果用户的status为禁用。那么就抛出<code>DisabledAccountException</code>
			 */
			throw new AccountException("帐号或密码不正确！");
		}else if(UUser._0.equals(user.getStatus())){
			throw new DisabledAccountException("帐号已经禁止登录！");
		}else{
			//更新登录时间 last login time
			user.setLastLoginTime(new Date());
			//userService.updateByPrimaryKeySelective(user);
		}
		AuthenticationInfo authcInfo=new SimpleAuthenticationInfo(user,user.getPswd(),getName());
		return authcInfo;
	}
	
	private UUser getUser(String userEname) {
		UUser user = new UUser();
		user.setEmail(userEname);
		user.setPswd(userEname);
		user.setStatus(UUser._1);
		return user;
	}
	/**
     * 清空当前用户权限信息
     */
	public  void clearCachedAuthorizationInfo() {
		PrincipalCollection principalCollection = SecurityUtils.getSubject().getPrincipals();
		SimplePrincipalCollection principals = new SimplePrincipalCollection(
				principalCollection, getName());
		super.clearCachedAuthorizationInfo(principals);
	}
	/**
	 * 指定principalCollection 清除
	 */
	public void clearCachedAuthorizationInfo(PrincipalCollection principalCollection) {
		SimplePrincipalCollection principals = new SimplePrincipalCollection(
				principalCollection, getName());
		super.clearCachedAuthorizationInfo(principals);
	}
}
